package handler

import (
	"ecom-mgr/cache"
	"ecom-mgr/model"
	"encoding/json"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {

	title := c.PostForm("title")
	desc := c.PostForm("desc")

	var book model.Book
	book.Title = title
	book.Desc = desc

	err := model.DB.Create(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "发布失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})

}

func Del(c *gin.Context) {

	id := c.PostForm("id")
	var book model.Book

	err := model.DB.Where("id = ?", id).Debug().Delete(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "删除失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}

func List(c *gin.Context) {

	var book []model.Book

	redis_list_key := "redis_list"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()

	if result == "" {
		model.DB.Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &book)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表成功",
		"data": book,
	})
	return

}
